package DAO

import (
	"CSMS/database"
	"CSMS/funclib"
	"database/sql"
	"fmt"
	"github.com/gin-gonic/gin"
)

type User struct {
	UserNo       int            `db:"UserNo"`
	UserLoginId  sql.NullString `db:"UserLoginId"`
	UserName     sql.NullString `db:"UserName"`
	UserPassword sql.NullString `db:"UserPassword"`
	UserRank     sql.NullString `db:"UserRank"`
}

type UGC struct {
	User        User
	Consignment Consignment
	Indent      Indent
}

//SelectUserById 通过 用户登录ID 选择一个用户的所有信息
func (user *User) SelectUserByLoginId(loginId string) bool {
	row := database.DB.QueryRow("SELECT * FROM user WHERE UserLoginId=?", loginId)
	err := row.Scan(&user.UserNo, &user.UserLoginId, &user.UserName, &user.UserPassword, &user.UserRank)
	if err != nil {
		fmt.Println(err, "User.go")
		return false
	}
	return true
}

//SelectUserByNo 通过 用户号 选择一个用户的所有信息
func (user *User) SelectUserByNo(No string) bool {
	row := database.DB.QueryRow("SELECT * FROM user WHERE UserNo=?", No)
	err := row.Scan(&user.UserNo, &user.UserLoginId, &user.UserName, &user.UserPassword, &user.UserRank)
	if err != nil {
		fmt.Println(err, "User.go")
		return false
	}
	return true
}

//SelectByNowMonth 搜索当月的用户信息
func SelectByNowMonth(nowDateYear, nowDateMonth string) []gin.H {
	var nowMonthInfoJSON []gin.H
	var ugc UGC
	rows, err := database.DB.Query("SELECT * FROM permonthuser WHERE IndentDate>=? AND IndentDate<=?", nowDateYear+"-"+nowDateMonth+"-01", nowDateYear+"-"+nowDateMonth+"-"+funclib.JudgeMonthDay(nowDateMonth))
	if err != nil {
		fmt.Println(err, "User.go:51")
		return nowMonthInfoJSON
	}
	defer func() {
		if rows != nil {
			rows.Close() //可以关闭掉未scan连接一直占用
		}
	}()
	for rows.Next() {
		err = rows.Scan(&ugc.User.UserNo, &ugc.Consignment.ConsignmentName, &ugc.User.UserName, &ugc.Consignment.ConsignmentName, &ugc.Consignment.ConsignmentAdr, &ugc.Indent.IndentDate)
		if err != nil {
			fmt.Println(err, "User.go:64")
			return nowMonthInfoJSON
		}
		nowMonthInfoJSON = append(nowMonthInfoJSON, gin.H{
			"UserNo":          ugc.User.UserNo,
			"ConsignmentName": ugc.Consignment.ConsignmentName,
			"UserName":        ugc.User.UserName,
			"ConsignmentTel":  ugc.Consignment.ConsignmentName,
			"ConsignmentAdr":  ugc.Consignment.ConsignmentAdr,
		})
	}
	return nowMonthInfoJSON
}
